package com.aliang.book_java1.po.springboot整合SSE;

// 导入相关依赖
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class SseController {

    @GetMapping("/stream")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();

        System.out.println("-------------1111");
        // 在新线程中发送事件以避免阻塞主线程
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    emitter.send("data:" + i + ";当前转换文件1111"); // 发送数据
                    Thread.sleep(10000); // 每秒发送一次
                }
                emitter.complete(); // 完成发送
            } catch (Exception e) {
                emitter.completeWithError(e); // 发送异常
            }
        }).start();

        return emitter;
    }
}
